package com.java.agent.bytebuddy;

import com.java.agent.enhance.BaseDefiner;
import com.java.agent.util.LoadClass;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.utility.JavaModule;

import java.lang.instrument.Instrumentation;

public class MonitorAgent {

    public static void premain(String agentArgs, Instrumentation instrumentation) throws Exception {

        LoadClass.getClasses( BaseDefiner.class.getPackageName()+".definer" );

        new AgentBuilder.Default()
                .with(new AgentBuilder.Listener() {
                    @Override
                    public void onDiscovery(String s, ClassLoader classLoader, JavaModule javaModule, boolean b) {
                    }

                    @Override
                    public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, boolean b, DynamicType dynamicType) {
                    }

                    @Override
                    public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, boolean b) {
                    }

                    @Override
                    public void onError(String s, ClassLoader classLoader, JavaModule javaModule, boolean b, Throwable throwable) {
                        System.out.println(throwable);
                    }

                    @Override
                    public void onComplete(String s, ClassLoader classLoader, JavaModule javaModule, boolean b) {
                    }
                })
                .type(BaseDefiner.matchs())
                .transform(((builder, typeDescription, classLoader, module) -> {
                    DynamicType.Builder<?> newBuilder = builder;
                    try {
                        newBuilder = BaseDefiner.getRuntime(typeDescription.getTypeName()).enhanced(builder, typeDescription, classLoader, module);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return newBuilder;
                })).installOn(instrumentation);
    }

}



//private static class Transformer implements AgentBuilder.Transformer {
//    return null;
//}
